<template>
  <div>
    <el-card v-if="isShow === 1">
      <!-- =======================标题============开始========================= -->
      <div slot="header" class="clearfix">
        <span style="font-weight: 700">新增试卷</span>
        <el-button
          style="float: right"
          size="small"
          plain
          type="primary"
          @click="editIsShow"
          >返回列表</el-button
        >
      </div>
      <!-- =======================标题============结束========================= -->

      <!-- =======================表格区域============开始========================= -->
      <el-form
        ref="formRef"
        :model="queryData"
        label-width="80px"
        :rules="rules"
      >
        <el-row>
          <el-col id="zhulxcol" :span="12">
            <el-form-item label="试卷名称" prop="paper_name">
              <el-input
                size="small"
                placeholder="请输入试卷名称"
                v-model="queryData.paper_name"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col id="zhulxcol" :span="12">
            <el-form-item
              label="试卷包含题型"
              label-width="110px"
              prop="check_question_list"
            >
              <el-checkbox-group
                @change="handleCheckChange"
                v-model="tempData.checkBox_list"
              >
                <el-checkbox label="单选题" name="checkBox_list"></el-checkbox>
                <el-checkbox label="多选题" name="checkBox_list"></el-checkbox>
                <el-checkbox label="判断题" name="checkBox_list"></el-checkbox>
                <el-checkbox label="简答题" name="checkBox_list"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <!-- 第二行 -->
          <el-col id="zhulxcol" :span="6">
            <el-form-item label="归属学科" prop="subject_id">
              <el-select
                clearable
                size="small"
                v-model="queryData.subject_id"
                placeholder="请选择归属学科"
                @change="selectSubjectId($event)"
              >
                <!-- v-for 渲染 -->
                <el-option
                  v-for="item in subjectData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col id="zhulxcol" :span="6">
            <el-form-item label="归属目录" prop="directory_id">
              <el-select
                clearable
                size="small"
                v-model="queryData.directory_id"
                placeholder="请选择归属目录"
              >
                <el-option
                  v-for="item in subjectChild"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col id="zhulxcol" :span="6">
            <el-form-item label="试卷状态">
              <el-radio-group v-model="queryData.show_state">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="2">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col id="zhulxcol" :span="6">
            <el-form-item label="试卷类型">
              <el-radio-group v-model="queryData.paper_type">
                <el-radio :label="1">模拟卷</el-radio>
                <el-radio :label="2">考试卷</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- 第三行 -->
          <el-col id="zhulxcol" :span="6">
            <el-form-item label="试卷总分" prop="total_score">
              <el-input size="small" v-model="queryData.total_score">
                <template slot="append">分</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col id="zhulxcol" :span="6">
            <el-form-item label="及格分数" prop="pass_score">
              <el-input
                size="small"
                placeholder="请输入试卷名称"
                v-model="queryData.pass_score"
              >
                <template slot="append">分</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col id="zhulxcol" :span="12">
            <el-form-item label="试卷难度" prop="difficulty">
              <el-select
                size="small"
                clearable
                v-model="queryData.difficulty"
                placeholder="请选择试卷难度"
              >
                <!-- v-for 渲染 -->
                <el-option label="简单" :value="1"></el-option>
                <el-option label="中等" :value="2"></el-option>
                <el-option label="较难" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第四行 -->
        <el-row>
          <el-form-item label="选题信息">
            <el-table
              size="large"
              border
              empty-text="请勾选试卷包含题型，从而生成选题模板"
              :data="queryData.check_question_list"
              style="width: 100%"
            >
              <el-table-column
                header-align="center"
                prop="name"
                label="题型"
                width="100"
              >
                <template slot-scope="scope" width="1000">
                  {{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column label="选题信息" width="1000">
                <template slot-scope="scope" width="1000">
                  <el-row>
                    <el-col :span="3">
                      共
                      <el-input
                        size="small"
                        v-model.number="scope.row.num"
                        style="width: 60px"
                      ></el-input>
                      题,
                    </el-col>
                    <el-col :span="3">
                      每题
                      <el-input
                        v-model.number="scope.row.score"
                        size="small"
                        style="width: 60px"
                      ></el-input>
                      分,
                    </el-col>
                    <!-- -->
                    <el-col :span="5"
                      >已选题数:
                      <el-input
                        v-model.number="scope.row.check_list.length"
                        disabled
                        size="small"
                        style="width: 60px; color: blue"
                      ></el-input
                      >题
                    </el-col>
                    <el-col :span="6">
                      <el-button
                        type="success"
                        size="small"
                        @click="lookPaperInfoFn(scope.row.type)"
                        >看题</el-button
                      >
                      <el-button
                        type="primary"
                        size="small"
                        @click="selectPaperFn(scope.row.type, scope.row.name)"
                        >选题</el-button
                      >
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('formRef')">{{
            zhulx ? "立即修改" : "立即创建"
          }}</el-button>
          <el-button @click="editIsShow">取消</el-button>
        </el-form-item>
      </el-form>
      <!-- =======================表格区域============开始========================= -->
    </el-card>
    <!-- ============================查看================= -->
    <el-card v-else-if="isShow === 2">查看</el-card>
    <!-- ============================修改======================= -->
    <el-card v-else>修改</el-card>
    <!-- 选择题目组件 -->
    <selectPaper
      ref="selectPaperRef"
      :PaginationInfo="PaginationInfo"
      :title="title"
      :type="type"
      @skipPage="skipPage"
      @EditFn="EditFn"
      @update="updateFn"
      :tableData="tableData"
      :subjectData="subjectData"
      :selectedQuest="selectedQuest"
    />
    <!-- 查看题目  -->
    <checkQuest
      ref="checkQuestRef"
      @notify="notify"
      :quest_type="quest_type"
      :resultQuestData="resultQuestData"
      @delData="delData"
    />
  </div>
</template>

<script>
import checkQuest from "./checkQuest.vue";
import selectPaper from "./selectPaper.vue";
import {
  addPaperInfoListApi,
  selectPaperInfoApi,
  aeditPaperInfoListApi,
} from "@/api/paperInfo.js";
export default {
  name: "addPaper",
  props: {
    isShow: {
      type: Number,
      required: true,
    },
    subjectData: {
      type: Array,
      required: true,
    },
    editpaperInfoData: {
      type: Object,
      required: true,
    },
    zhulx: {
      type: Boolean,
      default: false,
    },
    id: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      selectedQuest: [],
      //   zhulx: true,
      quest_type: 0,
      title: "选择题目",
      PaginationInfo: {},
      // 验证
      type: 0,
      tableData: {},
      total: 0,
      //   total:selectPaperList.length
      // 选中的数据
      selectList: [],
      isSame: false,
      // 校验规则
      rules: {
        paper_name: [
          { required: true, message: "请输入试卷名称", trigger: "blur" },
        ],
        total_score: [
          { required: true, message: "请输入总分", trigger: "blur" },
        ],
        pass_score: [
          { required: true, message: "请输入及格分数", trigger: "blur" },
        ],
        difficulty: [
          { required: true, message: "请选择试卷难度", trigger: "change" },
        ],
        subject_id: [
          { required: true, message: "请选择试卷难度", trigger: "change" },
        ],
        directory_id: [
          { required: true, message: "请选择试卷难度", trigger: "change" },
        ],
        paper_type: [
          { required: true, message: "请选择试卷难度", trigger: "change" },
        ],
        check_question_list: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个试卷题型",
            trigger: "change",
          },
        ],
      },
      // 临时数据
      tempData: {
        checkBox_list: [],
      },
      // 创建试卷的参数
      queryData: {
        // 选择的题型
        check_question_list: [],
        // 难度
        difficulty: "",
        // 归属学科
        directory_id: "",
        // 试卷名称
        paper_name: "",
        paper_type: 2,
        // 及格分
        pass_score: 60,
        quest_type: [],
        question_list: [],
        show_state: 1,
        subject_id: "",
        // 总分
        total_score: 100,
      },
      //
      fedbackQueryData: {},
      // 选题的参数
      selectData: {
        page: 1,
        limit: 10,
        subject_id: "",
        directory_id: "",
        tag_id: "",
        difficulty: "",
        // 必选参数
        quest_type: 0,
        is_true_question: "",
        show_state: 1,
        check_state: 2,
        create_name: "",
        create_time: "",
      },
      // 归属学科的子集 归属目录
      subjectChild: [],
      // 获取到数据并传递给子组件 select 去完成渲染
      selectPaperList: [],
      arrList: [
        {
          type: 1,
          name: "单选题",
          num: 0,
          score: 0,
          check_list: [],
        },
        {
          type: 2,
          name: "多选题",
          num: 0,
          score: 0,
          check_list: [],
        },
        {
          type: 3,
          name: "判断题",
          num: 0,
          score: 0,
          check_list: [],
        },
        {
          type: 4,
          name: "简答题",
          num: 0,
          score: 0,
          check_list: [],
        },
      ],
      resultQuestData: [],
    };
  },

  // 在 created 的里面回显数据
  created() {
    if (this.zhulx) {
      // ps：一级数据不需要响应式数据   二级数据会没有响应式 所以要使用 $set 添加响应式
      this.queryData.paper_name = this.editpaperInfoData.paper_name;
      // 回显 信息的个数
      JSON.parse(this.editpaperInfoData.check_question_list).forEach((item) => {
        if (JSON.parse(this.editpaperInfoData.quest_type).includes(item.type)) {
          //   console.log(item);
          //   console.log(this.queryData.check_question_list[item.type]);
          // 吧对应的题型信息赋值给 queryData
          this.queryData.check_question_list.push(item);
          console.log(this.queryData.check_question_list);
        }
      });
      // 回显 check_list 的真实数据
      this.editpaperInfoData.question_data.forEach((item) => {
        this.queryData.check_question_list.forEach((ele) => {
          if (ele.type === item.quest_type) {
            console.log(ele); // 把对应的题目往对应的题型上添加
            ele.check_list.push(item);
          }
        });
      });
      // 回显
      this.queryData.subject_id = this.editpaperInfoData.subject_id;
      this.queryData.directory_id = this.editpaperInfoData.directory_id;
      // 是否启用
      this.queryData.show_state = this.editpaperInfoData.show_state;
      //  试卷难度
      this.queryData.difficulty = this.editpaperInfoData.difficulty;
      // 试卷题型
      this.queryData.quest_type = JSON.parse(this.editpaperInfoData.quest_type);
      // 回显选择的状态
      JSON.parse(this.editpaperInfoData.quest_type).forEach((item) => {
        if (item === 1) {
          this.tempData.checkBox_list.push("单选题");
        } else if (item === 2) {
          this.tempData.checkBox_list.push("多选题");
        } else if (item === 3) {
          this.tempData.checkBox_list.push("判断题");
        } else if (item === 4) {
          this.tempData.checkBox_list.push("简答题");
        }
      });
      // 试卷类型
      this.queryData.paper_type = this.editpaperInfoData.paper_type;
    }
  },
  components: { selectPaper, checkQuest },
  methods: {
    // 定义一个获取选题的方法 获取数据
    async initData() {
      try {
        this.tableData = await selectPaperInfoApi(this.selectData);
      } catch (error) {
        return console.log(error);
      }
      // 处理分页的信息数据
      this.PaginationInfo = {
        page: this.selectData.page,
        limit: this.selectData.limit,
        total: this.tableData.total,
      };
      // 调用回显函数 backData
      this.$nextTick(() => {
        this.$refs.selectPaperRef.backData();
        this.$refs.selectPaperRef.dialogVisible = true;
      });
    },
    // 创建试卷 按钮  && 修改数据  复用
    async onSubmit(formRef) {
      let flag = false;
      // 1. 首先手动校验表单
      try {
        await this.$refs.formRef.validate();
      } catch (error) {
        this.$message.warning("检查提交数据，校验失败");
        return console.log(error);
      }
      // 每次进来前都要重置 不然会累加数据项
      this.queryData.question_list = [];
      //  获取所有题目的 id 数组 check_question_list 是题型（单选、多选等）
      this.queryData.check_question_list.forEach((item, index) => {
        // quest_type 是题型的标识（选中的）
        const arr = item.check_list.map((ele) => {
          return ele.id; // 筛选出 id
        });
        this.queryData.question_list = [
          ...this.queryData.question_list,
          ...arr,
        ];
        this.queryData.question_list = [
          ...new Set(this.queryData.question_list),
        ]; // 注意数组的去重
        /*****
         * 逻辑判断 校验
         */
        if (item.check_list.length === 0) {
          return this.$message.error(`你没有选择${item.name}的题目`);
        } else if (item.score === 0) {
          return this.$message.error(`${item.name}分数为空`);
        } else if (item.num === 0) {
          return this.$message.error(`${item.name}的题目数量为空`);
        } else if (item.num !== item.check_list.length) {
          return this.$message.error(`${item.name}的选题数量和试题数量不一致`);
        } else {
          flag = true;
        }
        console.log(index);
        // 一个人通关不可以 所有人都通关才能执行   BUG 只会一次校验
        if (index === this.queryData.check_question_list.length) {
          //   flag = true;
          console.log(index);
        }
      });
      // 2. 逻辑校验 选题的数量校验 分数的校验
      if (flag) {
        console.log("我被执行了");
        this.queryData.check_question_list.forEach((item) => {
          // 要清空所选择的所有数据 不然不能成功请求数据
          item.check_list = [];
        });
        try {
          if (this.zhulx) {
            // 修改位置
            console.log("修改位置", this.id);
            this.queryData.id = this.id;
            console.log(this.queryData.id);
            await aeditPaperInfoListApi(this.queryData);
          } else {
            // 创建位置
            await addPaperInfoListApi(this.queryData);
          }
        } catch (error) {
          return console.log(error);
        }
        this.$emit("okState");
      }
    },
    // 复选框动态添加信息  这是添加题型的  quest_type 数组
    handleCheckChange(arr) {
      const newArr = this.arrList.filter((item) => {
        if (arr.includes(item.name)) {
          return item;
        }
        return;
      });
      //   console.log(newArr);
      // 让其不要相互影响 减小依赖的关系
      this.queryData.check_question_list = newArr;
      // 获取 quest_type 数组参数
      this.queryData.quest_type = this.queryData.check_question_list.map(
        (item) => {
          return item.type;
        }
      );
      console.log(this.queryData.quest_type);
    },
    // 返回列表  通知父组件修改数据
    editIsShow() {
      this.$emit("update", 0);
    },
    // 二级联动
    selectSubjectId(id) {
      const obj = this.subjectData.filter((item) => {
        return item.id === id;
      });
      this.subjectChild = obj[0].children;
    },
    // 选则题目的按钮  打开面板  && 回显数据  手动去回显数据
    async selectPaperFn(type, name) {
      this.queryData.check_question_list.forEach((item) => {
        if (type === item.type) {
          this.selectedQuest = item.check_list;
        }
      });

      //   console.log(this.$refs.selectPaperRef);
      this.title = name;
      this.type = type;
      this.selectData.quest_type = type;
      this.initData();
    },
    // 选择题目  更新视图 获取子组件选取的题目  获取到预览的题目
    updateFn(val, type) {
      this.queryData.check_question_list.forEach((item) => {
        if (item.type === type) {
          item.check_list = val; // 可以动态的更新长度
        }
      });
    },
    // 分页 换页函数
    skipPage(str, val) {
      str === "page"
        ? (this.selectData.page = val)
        : (this.selectData.limit = val);
      this.initData();
    },
    // 看题  拿到所选的数据 然后渲染即可  筛选出要查看的数据即可
    lookPaperInfoFn(type) {
      this.quest_type = type;
      this.queryData.check_question_list.forEach((item) => {
        if (item.type === type) {
          this.resultQuestData = item.check_list;
        }
      });
      this.$refs.checkQuestRef.dialogVisible = true;
    },
    EditFn(val) {
      this.selectData = val;
      this.initData();
    },
    // 预览图片的时候删除
    delData(idx, type) {
      this.queryData.check_question_list.forEach((item) => {
        if (item.type === type) {
          item.check_list.splice(idx, 1);
        }
      });
    },
    notify(lng, arr, type) {
      //   console.log(this.queryData.check_question_list);
      this.arrList[type - 1].selectedNum = lng;
    },
    // 定义一个回显数据的方法
    fedbackDatasd() {
      console.log("定义一个回显数据的方法用来回显数据");
    },
  },
};
</script>

<style scoped>
#zhulxcol {
  height: 60px;
}
#eldialog__body {
  padding: 0 !important;
}
.titleInfo {
  display: inline-block;
}
.title {
  color: gray;
}
</style>
